# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  
@software: PyCharm 
@file: class_mixins1.py 
@time: 2019/6/25 15:44
"""
'''
利用Mixins(混入类)扩展类功能
1.通过使用装饰器实现混入类的方式
'''

def LoggedMapping(cls):
    """
    使用类装饰器
    :param cls:
    :return:
    """
    cls_getitem = cls.__getitem__
    cls_setitem = cls.__setitem__
    cls_delitem = cls.__delitem__

    def __getitem__(self, key):
        print('Getting ' + str(key))
        return cls_getitem(self, key)

    def __setitem__(self, key, value):
        print('Setting {} = {!r}'.format(key, value))
        return cls_setitem(self, key, value)

    def __delitem__(self, key):
        print('Deleting ' + str(key))
        return cls_delitem(self, key)

    cls.__getitem__ = __getitem__
    cls.__setitem__ = __setitem__
    cls.__delitem__ = __delitem__

    return cls

# Example use
@LoggedMapping
class LoggedDict(dict):
    pass

d = LoggedDict()
d['x'] = [3, 4]
d['x'] = [4, 5]
d['x'][1] = 6
print(d)
del d['x'][0]
print(d)

